Test Failed
Push — master ( 241100...2372f3 )
by Stream
08:09 queued 10s
created

script.js ➔ usingCkeditor3   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
dl 0
loc 3
rs 10
1
var lfm_route = location.origin + location.pathname;
2
var show_list;
3
var sort_type = 'alphabetic';
4
var multi_selection_enabled = false;
5
var selected = [];
6
var items = [];
7
8
$.fn.fab = function (options) {
9
  var menu = this;
10
  menu.addClass('fab-wrapper');
11
12
  var toggler = $('<a>')
13
    .addClass('fab-button fab-toggle')
14
    .append($('<i>').addClass('fas fa-plus'))
15
    .click(function () {
16
      menu.toggleClass('fab-expand');
17
    });
18
19
  menu.append(toggler);
20
21
  options.buttons.forEach(function (button) {
22
    toggler.before(
23
      $('<a>').addClass('fab-button fab-action')
24
        .attr('data-label', button.label)
25
        .attr('id', button.attrs.id)
26
        .append($('<i>').addClass(button.icon))
27
        .click(function () {
28
          menu.removeClass('fab-expand');
29
        })
30
    );
31
  });
32
};
33
34
$(document).ready(function () {
35
  $('#fab').fab({
36
    buttons: [
37
      {
38
        icon: 'fas fa-upload',
39
        label: lang['nav-upload'],
0 ignored issues
show
Bug introduced by
The variable lang seems to be never declared. If this is a global, consider adding a /** global: lang */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
40
        attrs: {id: 'upload'}
41
      },
42
      {
43
        icon: 'fas fa-folder',
44
        label: lang['nav-new'],
45
        attrs: {id: 'add-folder'}
46
      }
47
    ]
48
  });
49
50
  actions.reverse().forEach(function (action) {
0 ignored issues
show
Bug introduced by
The variable actions seems to be never declared. If this is a global, consider adding a /** global: actions */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
51
    $('#nav-buttons > ul').prepend(
52
      $('<li>').addClass('nav-item').append(
53
        $('<a>').addClass('nav-link d-none')
54
          .attr('data-action', action.name)
55
          .attr('data-multiple', action.multiple)
56
          .append($('<i>').addClass('fas fa-fw fa-' + action.icon))
57
          .append($('<span>').text(action.label))
58
      )
59
    );
60
  });
61
62
  sortings.forEach(function (sort) {
0 ignored issues
show
Bug introduced by
The variable sortings seems to be never declared. If this is a global, consider adding a /** global: sortings */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
63
    $('#nav-buttons .dropdown-menu').append(
64
      $('<a>').addClass('dropdown-item').attr('data-sortby', sort.by)
65
        .append($('<i>').addClass('fas fa-fw fa-' + sort.icon))
66
        .append($('<span>').text(sort.label))
67
        .click(function() {
68
          sort_type = sort.by;
69
          loadItems();
70
        })
71
    );
72
  });
73
74
  loadFolders();
75
  performLfmRequest('errors')
76
    .done(function (response) {
77
      JSON.parse(response).forEach(function (message) {
78
        $('#alerts').append(
79
          $('<div>').addClass('alert alert-warning')
80
            .append($('<i>').addClass('fas fa-exclamation-circle'))
81
            .append(' ' + message)
82
        );
83
      });
84
    });
85
86
  $(window).on('dragenter', function(){
87
    $('#uploadModal').modal('show');
88
  });
89
90
  if (usingWysiwygEditor()) {
91
    $('#multi_selection_toggle').hide();
92
  }
93
});
94
95
// ======================
96
// ==  Navbar actions  ==
97
// ======================
98
99
$('#multi_selection_toggle').click(function () {
100
  multi_selection_enabled = !multi_selection_enabled;
101
102
  $('#multi_selection_toggle i')
103
    .toggleClass('fa-times', multi_selection_enabled)
104
    .toggleClass('fa-check-double', !multi_selection_enabled);
105
106
  if (!multi_selection_enabled) {
107
    clearSelected();
108
  }
109
});
110
111
$('#to-previous').click(function () {
112
  var previous_dir = getPreviousDir();
113
  if (previous_dir == '') return;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
114
  goTo(previous_dir);
115
});
116
117
function toggleMobileTree(should_display) {
118
  if (should_display === undefined) {
119
    should_display = !$('#tree').hasClass('in');
120
  }
121
  $('#tree').toggleClass('in', should_display);
122
}
123
124
$('#show_tree').click(function (e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
125
  toggleMobileTree();
126
});
127
128
$('#main').click(function (e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
129
  if ($('#tree').hasClass('in')) {
130
    toggleMobileTree(false);
131
  }
132
});
133
134
$(document).on('click', '#add-folder', function () {
135
  dialog(lang['message-name'], '', createFolder);
0 ignored issues
show
Bug introduced by
The variable lang seems to be never declared. If this is a global, consider adding a /** global: lang */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
136
});
137
138
$(document).on('click', '#upload', function () {
139
  $('#uploadModal').modal('show');
140
});
141
142
$(document).on('click', '[data-display]', function() {
143
  show_list = $(this).data('display');
144
  loadItems();
145
});
146
147
$(document).on('click', '[data-action]', function() {
148
  window[$(this).data('action')]($(this).data('multiple') ? getSelectedItems() : getOneSelectedElement());
149
});
150
151
// ==========================
152
// ==  Multiple Selection  ==
153
// ==========================
154
155
function toggleSelected (e) {
156
  if (!multi_selection_enabled) {
157
    selected = [];
158
  }
159
160
  var sequence = $(e.target).closest('a').data('id');
161
  var element_index = selected.indexOf(sequence);
162
  if (element_index === -1) {
163
    selected.push(sequence);
164
  } else {
165
    selected.splice(element_index, 1);
166
  }
167
168
  updateSelectedStyle();
169
}
170
171
function clearSelected () {
172
  selected = [];
173
174
  multi_selection_enabled = false;
175
176
  updateSelectedStyle();
177
}
178
179
function updateSelectedStyle() {
180
  items.forEach(function (item, index) {
181
    $('[data-id=' + index + ']')
182
      .find('.square')
183
      .toggleClass('selected', selected.indexOf(index) > -1);
184
  });
185
  toggleActions();
186
}
187
188
function getOneSelectedElement(orderOfItem) {
189
  var index = orderOfItem !== undefined ? orderOfItem : selected[0];
190
  return items[index];
191
}
192
193
function getSelectedItems() {
194
  return selected.reduce(function (arr_objects, id) {
195
    arr_objects.push(getOneSelectedElement(id));
196
    return arr_objects
197
  }, []);
198
}
199
200
function toggleActions() {
201
  var one_selected = selected.length === 1;
202
  var many_selected = selected.length >= 1;
203
  var only_image = getSelectedItems()
204
    .filter(function (item) { return !item.is_image; })
205
    .length === 0;
206
  var only_file = getSelectedItems()
207
    .filter(function (item) { return !item.is_file; })
208
    .length === 0;
209
210
  $('[data-action=use]').toggleClass('d-none', !(many_selected && only_file));
211
  $('[data-action=rename]').toggleClass('d-none', !one_selected);
212
  $('[data-action=preview]').toggleClass('d-none', !(many_selected && only_file));
213
  $('[data-action=move]').toggleClass('d-none', !many_selected);
214
  $('[data-action=download]').toggleClass('d-none', !(many_selected && only_file));
215
  $('[data-action=resize]').toggleClass('d-none', !(one_selected && only_image));
216
  $('[data-action=crop]').toggleClass('d-none', !(one_selected && only_image));
217
  $('[data-action=trash]').toggleClass('d-none', !many_selected);
218
  $('[data-action=open]').toggleClass('d-none', !one_selected || only_file);
219
  $('#multi_selection_toggle').toggleClass('d-none', usingWysiwygEditor() || !many_selected);
220
  $('#actions').toggleClass('d-none', selected.length === 0);
221
  $('#fab').toggleClass('d-none', selected.length !== 0);
222
}
223
224
// ======================
225
// ==  Folder actions  ==
226
// ======================
227
228
$(document).on('click', '#tree a', function (e) {
229
  goTo($(e.target).closest('a').data('path'));
230
  toggleMobileTree(false);
231
});
232
233
function goTo(new_dir) {
234
  $('#working_dir').val(new_dir);
235
  loadItems();
236
}
237
238
function getPreviousDir() {
239
  var working_dir = $('#working_dir').val();
240
  return working_dir.substring(0, working_dir.lastIndexOf('/'));
241
}
242
243
function setOpenFolders() {
244
  $('#tree [data-path]').each(function (index, folder) {
245
    // close folders that are not parent
246
    var should_open = ($('#working_dir').val() + '/').startsWith($(folder).data('path') + '/');
247
    $(folder).children('i')
248
      .toggleClass('fa-folder-open', should_open)
249
      .toggleClass('fa-folder', !should_open);
250
  });
251
252
  $('#tree .nav-item').removeClass('active');
253
  $('#tree [data-path="' + $('#working_dir').val() + '"]').parent('.nav-item').addClass('active');
254
}
255
256
// ====================
257
// ==  Ajax actions  ==
258
// ====================
259
260
function performLfmRequest(url, parameter, type) {
261
  var data = defaultParameters();
262
263
  if (parameter != null) {
0 ignored issues
show
Best Practice introduced by
Comparing parameter to null using the != operator is not safe. Consider using !== instead.
Loading history...
264
    $.each(parameter, function (key, value) {
265
      data[key] = value;
266
    });
267
  }
268
269
  return $.ajax({
270
    type: 'GET',
271
    beforeSend: function(request) {
272
      var token = getUrlParam('token');
273
      if (token !== null) {
274
        request.setRequestHeader("Authorization", 'Bearer ' + token);
275
      }
276
    },
277
    dataType: type || 'text',
278
    url: lfm_route + '/' + url,
279
    data: data,
280
    cache: false
281
  }).fail(function (jqXHR, textStatus, errorThrown) {
0 ignored issues
show
Unused Code introduced by
The parameter textStatus is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter errorThrown is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
282
    displayErrorResponse(jqXHR);
283
  });
284
}
285
286
function displayErrorResponse(jqXHR) {
287
  notify('<div style="max-height:50vh;overflow: scroll;">' + jqXHR.responseText + '</div>');
288
}
289
290
var refreshFoldersAndItems = function (data) {
291
  loadFolders();
292
  if (data != 'OK') {
293
    data = Array.isArray(data) ? data.join('<br/>') : data;
294
    notify(data);
295
  }
296
};
297
298
var hideNavAndShowEditor = function (data) {
299
  $('#nav-buttons > ul').addClass('d-none');
300
  $('#content').html(data);
301
  $('#pagination').removeClass('preserve_actions_space')
302
  clearSelected();
303
}
304
305
function loadFolders() {
306
  performLfmRequest('folders', {}, 'html')
307
    .done(function (data) {
308
      $('#tree').html(data);
309
      loadItems();
310
    });
311
}
312
313
function generatePaginationHTML(el, args) {
314
  var template = '<li class="page-item"><\/li>';
315
  var linkTemplate = '<a class="page-link"><\/a>';
316
  var currentPage = args.currentPage;
317
  var totalPage = args.totalPage;
318
  var rangeStart = args.rangeStart;
319
  var rangeEnd = args.rangeEnd;
320
  var i;
321
322
  // Disable page range, display all the pages
323
  if (args.pageRange === null) {
324
    for (i = 1; i <= totalPage; i++) {
325
      var button = $(template)
326
        .attr('data-num', i)
327
        .append($(linkTemplate).html(i));
328
      if (i == currentPage) {
329
        button.addClass('active');
330
      }
331
      el.append(button);
332
    }
333
334
    return;
335
  }
336
337
  if (rangeStart <= 3) {
338
    for (i = 1; i < rangeStart; i++) {
339
      var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 325. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
340
        .attr('data-num', i)
341
        .append($(linkTemplate).html(i));
342
      if (i == currentPage) {
343
        button.addClass('active');
344
      }
345
      el.append(button);
346
    }
347
  } else {
348
    var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 325. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
349
      .attr('data-num', 1)
350
      .append($(linkTemplate).html(1));
351
    el.append(button);
352
353
    var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 325. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
354
      .addClass('disabled')
355
      .append($(linkTemplate).html('...'));
356
    el.append(button);
357
  }
358
359
  for (i = rangeStart; i <= rangeEnd; i++) {
360
    var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 325. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
361
      .attr('data-num', i)
362
      .append($(linkTemplate).html(i));
363
    if (i == currentPage) {
364
      button.addClass('active');
365
    }
366
    el.append(button);
367
  }
368
369
  if (rangeEnd >= totalPage - 2) {
370
    for (i = rangeEnd + 1; i <= totalPage; i++) {
371
      var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 325. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
372
        .attr('data-num', i)
373
        .append($(linkTemplate).html(i));
374
      el.append(button);
375
    }
376
  } else {
377
    var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 325. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
378
      .addClass('disabled')
379
      .append($(linkTemplate).html('...'));
380
    el.append(button);
381
382
    var button = $(template)
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable button already seems to be declared on line 325. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
383
      .attr('data-num', totalPage)
384
      .append($(linkTemplate).html(totalPage));
385
    el.append(button);
386
  }
387
}
388
389
function createPagination(paginationSetting) {
390
  var el = $('<ul class="pagination" role="navigation"></ul>');
391
392
  var currentPage = paginationSetting.current_page;
393
  var pageRange = 5;
394
  var totalPage = Math.ceil(paginationSetting.total / paginationSetting.per_page);
395
396
  var rangeStart = currentPage - pageRange;
397
  var rangeEnd = currentPage + pageRange;
398
399
  if (rangeEnd > totalPage) {
400
    rangeEnd = totalPage;
401
    rangeStart = totalPage - pageRange * 2;
402
    rangeStart = rangeStart < 1 ? 1 : rangeStart;
403
  }
404
405
  if (rangeStart <= 1) {
406
    rangeStart = 1;
407
    rangeEnd = Math.min(pageRange * 2 + 1, totalPage);
408
  }
409
410
  generatePaginationHTML(el, {
411
    totalPage: totalPage,
412
    currentPage: currentPage,
413
    pageRange: pageRange,
414
    rangeStart: rangeStart,
415
    rangeEnd: rangeEnd
416
  });
417
418
  $('#pagination').append(el);
419
}
420
421
function loadItems(page) {
422
  loading(true);
423
  performLfmRequest('jsonitems', {show_list: show_list, sort_type: sort_type, page: page || 1}, 'html')
424
    .done(function (data) {
425
      selected = [];
426
      var response = JSON.parse(data);
427
      var working_dir = response.working_dir;
428
      items = response.items;
429
      var hasItems = items.length !== 0;
430
      var hasPaginator = !!response.paginator;
431
      $('#empty').toggleClass('d-none', hasItems);
432
      $('#content').html('').removeAttr('class');
433
      $('#pagination').html('').removeAttr('class');
434
435
      if (hasItems) {
436
        $('#content').addClass(response.display);
437
        $('#pagination').addClass('preserve_actions_space');
438
439
        items.forEach(function (item, index) {
440
          var template = $('#item-template').clone()
441
            .removeAttr('id class')
442
            .attr('data-id', index)
443
            .click(toggleSelected)
444
            .dblclick(function (e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
445
              if (item.is_file) {
446
                use(getSelectedItems());
447
              } else {
448
                goTo(item.url);
449
              }
450
            });
451
452
          if (item.thumb_url) {
453
            var image = $('<div>').css('background-image', 'url("' + item.thumb_url + '?timestamp=' + item.time + '")');
454
          } else {
455
            var icon = $('<div>').addClass('ico');
456
            var image = $('<div>').addClass('mime-icon ico-' + item.icon).append(icon);
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable image already seems to be declared on line 453. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
457
          }
458
459
          template.find('.square').append(image);
460
          template.find('.item_name').text(item.name);
461
          template.find('time').text((new Date(item.time * 1000)).toLocaleString());
462
463
          $('#content').append(template);
464
        });
465
      }
466
467
      if (hasPaginator) {
468
        createPagination(response.paginator);
469
470
        $('#pagination a').on('click', function(event) {
471
          event.preventDefault();
472
473
          loadItems($(this).closest('li')[0].getAttribute('data-num'));
474
475
          return false;
476
        });
477
      }
478
479
      $('#nav-buttons > ul').removeClass('d-none');
480
481
      $('#working_dir').val(working_dir);
482
      console.log('Current working_dir : ' + working_dir);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
483
      var breadcrumbs = [];
484
      var validSegments = working_dir.split('/').filter(function (e) { return e; });
485
      validSegments.forEach(function (segment, index) {
486
        if (index === 0) {
487
          // set root folder name as the first breadcrumb
488
          breadcrumbs.push($("[data-path='/" + segment + "']").text());
489
        } else {
490
          breadcrumbs.push(segment);
491
        }
492
      });
493
494
      $('#current_folder').text(breadcrumbs[breadcrumbs.length - 1]);
495
      $('#breadcrumbs > ol').html('');
496
      breadcrumbs.forEach(function (breadcrumb, index) {
497
        var li = $('<li>').addClass('breadcrumb-item').text(breadcrumb);
498
499
        if (index === breadcrumbs.length - 1) {
500
          li.addClass('active').attr('aria-current', 'page');
501
        } else {
502
          li.click(function () {
503
            // go to corresponding path
504
            goTo('/' + validSegments.slice(0, 1 + index).join('/'));
505
          });
506
        }
507
508
        $('#breadcrumbs > ol').append(li);
509
      });
510
511
      var atRootFolder = getPreviousDir() == '';
512
      $('#to-previous').toggleClass('d-none invisible-lg', atRootFolder);
513
      $('#show_tree').toggleClass('d-none', !atRootFolder).toggleClass('d-block', atRootFolder);
514
      setOpenFolders();
515
      loading(false);
516
      toggleActions();
517
    });
518
}
519
520
function loading(show_loading) {
521
  $('#loading').toggleClass('d-none', !show_loading);
522
}
523
524
function createFolder(folder_name) {
525
  performLfmRequest('newfolder', {name: folder_name})
526
    .done(refreshFoldersAndItems);
527
}
528
529
// ==================================
530
// ==         File Actions         ==
531
// ==================================
532
533
function rename(item) {
534
  dialog(lang['message-rename'], item.name, function (new_name) {
0 ignored issues
show
Bug introduced by
The variable lang seems to be never declared. If this is a global, consider adding a /** global: lang */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
535
    performLfmRequest('rename', {
536
      file: item.name,
537
      new_name: new_name
538
    }).done(refreshFoldersAndItems);
539
  });
540
}
541
542
function trash(items) {
543
  notify(lang['message-delete'], function () {
0 ignored issues
show
Bug introduced by
The variable lang seems to be never declared. If this is a global, consider adding a /** global: lang */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
544
    performLfmRequest('delete', {
545
      items: items.map(function (item) { return item.name; })
546
    }).done(refreshFoldersAndItems)
547
  });
548
}
549
550
function crop(item) {
551
  performLfmRequest('crop', {img: item.name})
552
    .done(hideNavAndShowEditor);
553
}
554
555
function resize(item) {
556
  performLfmRequest('resize', {img: item.name})
557
    .done(hideNavAndShowEditor);
558
}
559
560
function download(items) {
561
  items.forEach(function (item, index) {
562
    var data = defaultParameters();
563
564
    data['file'] = item.name;
565
566
    var token = getUrlParam('token');
567
    if (token) {
568
      data['token'] = token;
569
    }
570
571
    setTimeout(function () {
572
      location.href = lfm_route + '/download?' + $.param(data);
573
    }, index * 100);
574
  });
575
}
576
577
function open(item) {
578
  goTo(item.url);
579
}
580
581
function preview(items) {
582
  var carousel = $('#carouselTemplate').clone().attr('id', 'previewCarousel').removeClass('d-none');
583
  var imageTemplate = carousel.find('.carousel-item').clone().removeClass('active');
584
  var indicatorTemplate = carousel.find('.carousel-indicators > li').clone().removeClass('active');
585
  carousel.children('.carousel-inner').html('');
586
  carousel.children('.carousel-indicators').html('');
587
  carousel.children('.carousel-indicators,.carousel-control-prev,.carousel-control-next').toggle(items.length > 1);
588
589
  items.forEach(function (item, index) {
590
    var carouselItem = imageTemplate.clone()
591
      .addClass(index === 0 ? 'active' : '');
592
593
    if (item.thumb_url) {
594
      carouselItem.find('.carousel-image').css('background-image', 'url(\'' + item.url + '?timestamp=' + item.time + '\')');
595
    } else {
596
      carouselItem.find('.carousel-image').css('width', '50vh').append($('<div>').addClass('mime-icon ico-' + item.icon));
597
    }
598
599
    carouselItem.find('.carousel-label').attr('target', '_blank').attr('href', item.url)
600
      .append(item.name)
601
      .append($('<i class="fas fa-external-link-alt ml-2"></i>'));
602
603
    carousel.children('.carousel-inner').append(carouselItem);
604
605
    var carouselIndicator = indicatorTemplate.clone()
606
      .addClass(index === 0 ? 'active' : '')
607
      .attr('data-slide-to', index);
608
    carousel.children('.carousel-indicators').append(carouselIndicator);
609
  });
610
611
612
  // carousel swipe control
613
  var touchStartX = null;
614
615
  carousel.on('touchstart', function (event) {
616
    var e = event.originalEvent;
617
    if (e.touches.length == 1) {
0 ignored issues
show
Best Practice introduced by
Comparing e.touches.length to 1 using the == operator is not safe. Consider using === instead.
Loading history...
618
      var touch = e.touches[0];
619
      touchStartX = touch.pageX;
620
    }
621
  }).on('touchmove', function (event) {
622
    var e = event.originalEvent;
623
    if (touchStartX != null) {
0 ignored issues
show
Best Practice introduced by
Comparing touchStartX to null using the != operator is not safe. Consider using !== instead.
Loading history...
624
      var touchCurrentX = e.changedTouches[0].pageX;
625
      if ((touchCurrentX - touchStartX) > 60) {
626
        touchStartX = null;
627
        carousel.carousel('prev');
628
      } else if ((touchStartX - touchCurrentX) > 60) {
629
        touchStartX = null;
630
        carousel.carousel('next');
631
      }
632
    }
633
  }).on('touchend', function () {
634
    touchStartX = null;
635
  });
636
  // end carousel swipe control
637
638
  notify(carousel);
639
}
640
641
function move(items) {
642
  performLfmRequest('move', { items: items.map(function (item) { return item.name; }) })
643
    .done(refreshFoldersAndItems);
644
}
645
646
function getUrlParam(paramName) {
647
  var reParam = new RegExp('(?:[\?&]|&)' + paramName + '=([^&]+)', 'i');
648
  var match = window.location.search.match(reParam);
649
  return ( match && match.length > 1 ) ? match[1] : null;
650
}
651
652
function use(items) {
653
  function useTinymce3(url) {
654
    if (!usingTinymce3()) { return; }
655
656
    var win = tinyMCEPopup.getWindowArg("window");
0 ignored issues
show
Bug introduced by
The variable tinyMCEPopup seems to be never declared. If this is a global, consider adding a /** global: tinyMCEPopup */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
657
    win.document.getElementById(tinyMCEPopup.getWindowArg("input")).value = url;
658
    if (typeof(win.ImageDialog) != "undefined") {
659
      // Update image dimensions
660
      if (win.ImageDialog.getImageData) {
661
        win.ImageDialog.getImageData();
662
      }
663
664
      // Preview if necessary
665
      if (win.ImageDialog.showPreviewImage) {
666
        win.ImageDialog.showPreviewImage(url);
667
      }
668
    }
669
    tinyMCEPopup.close();
670
  }
671
672
  function useTinymce4AndColorbox(url) {
673
    if (!usingTinymce4AndColorbox()) { return; }
674
675
    parent.document.getElementById(getUrlParam('field_name')).value = url;
0 ignored issues
show
Bug introduced by
The variable parent seems to be never declared. If this is a global, consider adding a /** global: parent */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
676
677
    if(typeof parent.tinyMCE !== "undefined") {
678
      parent.tinyMCE.activeEditor.windowManager.close();
679
    }
680
    if(typeof parent.$.fn.colorbox !== "undefined") {
681
      parent.$.fn.colorbox.close();
682
    }
683
  }
684
685
  function useTinymce5(url){
686
    if (!usingTinymce5()) { return; }
687
688
    parent.postMessage({
0 ignored issues
show
Bug introduced by
The variable parent seems to be never declared. If this is a global, consider adding a /** global: parent */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
689
      mceAction: 'insert',
690
      content: url
691
    });
692
693
    parent.postMessage({ mceAction: 'close' });
694
  }
695
696
  function useCkeditor3(url) {
697
    if (!usingCkeditor3()) { return; }
698
699
    if (window.opener) {
700
      // Popup
701
      window.opener.CKEDITOR.tools.callFunction(getUrlParam('CKEditorFuncNum'), url);
702
    } else {
703
      // Modal (in iframe)
704
      parent.CKEDITOR.tools.callFunction(getUrlParam('CKEditorFuncNum'), url);
0 ignored issues
show
Bug introduced by
The variable parent seems to be never declared. If this is a global, consider adding a /** global: parent */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
705
      parent.CKEDITOR.tools.callFunction(getUrlParam('CKEditorCleanUpFuncNum'));
706
    }
707
  }
708
709
  function useFckeditor2(url) {
710
    if (!usingFckeditor2()) { return; }
711
712
    var p = url;
713
    var w = data['Properties']['Width'];
0 ignored issues
show
Bug introduced by
The variable data seems to be never declared. If this is a global, consider adding a /** global: data */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
714
    var h = data['Properties']['Height'];
715
    window.opener.SetUrl(p,w,h);
716
  }
717
718
  var url = items[0].url;
719
  var callback = getUrlParam('callback');
720
  var useFileSucceeded = true;
721
722
  if (usingWysiwygEditor()) {
723
    useTinymce3(url);
724
725
    useTinymce4AndColorbox(url);
726
727
    useTinymce5(url);
728
729
    useCkeditor3(url);
730
731
    useFckeditor2(url);
732
  } else if (callback && window[callback]) {
733
    window[callback](getSelectedItems());
734
  } else if (callback && parent[callback]) {
0 ignored issues
show
Bug introduced by
The variable parent seems to be never declared. If this is a global, consider adding a /** global: parent */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
735
    parent[callback](getSelecteditems());
736
  } else if (window.opener) { // standalone button or other situations
737
    window.opener.SetUrl(getSelectedItems());
738
  } else {
739
    useFileSucceeded = false;
740
  }
741
742
  if (useFileSucceeded) {
743
    if (window.opener) {
744
      window.close();
745
    }
746
  } else {
747
    console.log('window.opener not found');
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
748
    // No editor found, open/download file using browser's default method
749
    window.open(url);
750
  }
751
}
752
//end useFile
753
754
// ==================================
755
// ==     WYSIWYG Editors Check    ==
756
// ==================================
757
758
function usingTinymce3() {
759
  return !!window.tinyMCEPopup;
760
}
761
762
function usingTinymce4AndColorbox() {
763
  return !!getUrlParam('field_name');
764
}
765
766
function usingTinymce5(){
767
    return !!getUrlParam('editor');
768
}
769
770
function usingCkeditor3() {
771
  return !!getUrlParam('CKEditor') || !!getUrlParam('CKEditorCleanUpFuncNum');
772
}
773
774
function usingFckeditor2() {
775
  return window.opener && typeof data != 'undefined' && data['Properties']['Width'] != '';
0 ignored issues
show
Bug introduced by
The variable data seems to be never declared. If this is a global, consider adding a /** global: data */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
776
}
777
778
function usingWysiwygEditor() {
779
  return usingTinymce3() || usingTinymce4AndColorbox() || usingTinymce5() || usingCkeditor3() || usingFckeditor2();
780
}
781
782
// ==================================
783
// ==            Others            ==
784
// ==================================
785
786
function defaultParameters() {
787
  return {
788
    working_dir: $('#working_dir').val(),
789
    type: $('#type').val()
790
  };
791
}
792
793
function notImp() {
794
  notify('Not yet implemented!');
795
}
796
797
function notify(body, callback) {
798
  $('#notify').find('.btn-primary').toggle(callback !== undefined);
799
  $('#notify').find('.btn-primary').unbind().click(callback);
800
  $('#notify').modal('show').find('.modal-body').html(body);
801
}
802
803
function dialog(title, value, callback) {
804
  $('#dialog').find('input').val(value);
805
  $('#dialog').on('shown.bs.modal', function () {
806
    $('#dialog').find('input').focus();
807
  });
808
  $('#dialog').find('.btn-primary').unbind().click(function (e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
809
    callback($('#dialog').find('input').val());
810
  });
811
  $('#dialog').modal('show').find('.modal-title').text(title);
812
}
813